/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import { app, BrowserWindow, contentTracing, dialog, ipcMain, protocol, session, Session, systemPreferences, WebFrameMain } from 'electron';
import { validatedIpcMain } from 'vs/base/parts/ipc/electron-main/ipcMain';
import { statSync } from 'fs';
import { hostname, release } from 'os';
import { VSBuffer } from 'vs/base/common/buffer';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { onUnexpectedError, setUnexpectedErrorHandler } from 'vs/base/common/errors';
import { isEqualOrParent, randomPath } from 'vs/base/common/extpath';
import { once } from 'vs/base/common/functional';
import { stripComments } from 'vs/base/common/json';
import { getPathLabel, mnemonicButtonLabel } from 'vs/base/common/labels';
import { Disposable } from 'vs/base/common/lifecycle';
import { FileAccess, Schemas } from 'vs/base/common/network';
import { isAbsolute, join, posix } from 'vs/base/common/path';
import { IProcessEnvironment, isLinux, isLinuxSnap, isMacintosh, isWindows, OS } from 'vs/base/common/platform';
import { assertType, withNullAsUndefined } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import { generateUuid } from 'vs/base/common/uuid';
import { getMachineId } from 'vs/base/node/id';
import { registerContextMenuListener } from 'vs/base/parts/contextmenu/electron-main/contextmenu';
import { getDelayedChannel, ProxyChannel, StaticRouter } from 'vs/base/parts/ipc/common/ipc';
import { Server as ElectronIPCServer } from 'vs/base/parts/ipc/electron-main/ipc.electron';
import { Client as MessagePortClient } from 'vs/base/parts/ipc/electron-main/ipc.mp';
import { Server as NodeIPCServer } from 'vs/base/parts/ipc/node/ipc.net';
import { ProxyAuthHandler } from 'vs/code/electron-main/auth';
import { localize } from 'vs/nls';
import { IBackupMainService } from 'vs/platform/backup/electron-main/backup';
import { BackupMainService } from 'vs/platform/backup/electron-main/backupMainService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ICredentialsMainService } from 'vs/platform/credentials/common/credentials';
import { ElectronExtensionHostDebugBroadcastChannel } from 'vs/platform/debug/electron-main/extensionHostDebugIpc';
import { IDiagnosticsService } from 'vs/platform/diagnostics/common/diagnostics';
import { DiagnosticsMainService, IDiagnosticsMainService } from 'vs/platform/diagnostics/electron-main/diagnosticsMainService';
import { DialogMainService, IDialogMainService } from 'vs/platform/dialogs/electron-main/dialogMainService';
import { IEncryptionMainService } from 'vs/platform/encryption/common/encryptionService';
import { EncryptionMainService } from 'vs/platform/encryption/node/encryptionMainService';
import { NativeParsedArgs } from 'vs/platform/environment/common/argv';
import { IEnvironmentMainService } from 'vs/platform/environment/electron-main/environmentMainService';
import { isLaunchedFromCli } from 'vs/platform/environment/node/argvHelper';
import { getResolvedShellEnv } from 'vs/platform/shell/node/shellEnv';
import { IExtensionUrlTrustService } from 'vs/platform/extensionManagement/common/extensionUrlTrust';
import { ExtensionUrlTrustService } from 'vs/platform/extensionManagement/node/extensionUrlTrustService';
import { IExtensionHostStarter, ipcExtensionHostStarterChannelName } from 'vs/platform/extensions/common/extensionHostStarter';
import { ExtensionHostStarter } from 'vs/platform/extensions/electron-main/extensionHostStarter';
import { IExternalTerminalMainService } from 'vs/platform/externalTerminal/common/externalTerminal';
import { LinuxExternalTerminalService, MacExternalTerminalService, WindowsExternalTerminalService } from 'vs/platform/externalTerminal/node/externalTerminalService';
import { LOCAL_FILE_SYSTEM_CHANNEL_NAME } from 'vs/platform/files/common/diskFileSystemProviderClient';
import { IFileService } from 'vs/platform/files/common/files';
import { DiskFileSystemProviderChannel } from 'vs/platform/files/electron-main/diskFileSystemProviderServer';
import { DiskFileSystemProvider } from 'vs/platform/files/node/diskFileSystemProvider';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { IIssueMainService, IssueMainService } from 'vs/platform/issue/electron-main/issueMainService';
import { IKeyboardLayoutMainService, KeyboardLayoutMainService } from 'vs/platform/keyboardLayout/electron-main/keyboardLayoutMainService';
import { ILaunchMainService, LaunchMainService } from 'vs/platform/launch/electron-main/launchMainService';
import { ILifecycleMainService, LifecycleMainPhase, ShutdownReason } from 'vs/platform/lifecycle/electron-main/lifecycleMainService';
import { ILoggerService, ILogService } from 'vs/platform/log/common/log';
import { LoggerChannel, LogLevelChannel } from 'vs/platform/log/common/logIpc';
import { IMenubarMainService, MenubarMainService } from 'vs/platform/menubar/electron-main/menubarMainService';
import { INativeHostMainService, NativeHostMainService } from 'vs/platform/native/electron-main/nativeHostMainService';
import { IProductService } from 'vs/platform/product/common/productService';
import { getRemoteAuthority } from 'vs/platform/remote/common/remoteHosts';
import { SharedProcess } from 'vs/platform/sharedProcess/electron-main/sharedProcess';
import { ISignService } from 'vs/platform/sign/common/sign';
import { IStateMainService } from 'vs/platform/state/electron-main/state';
import { StorageDatabaseChannel } from 'vs/platform/storage/electron-main/storageIpc';
import { GlobalStorageMainService, IGlobalStorageMainService, IStorageMainService, StorageMainService } from 'vs/platform/storage/electron-main/storageMainService';
import { resolveCommonProperties } from 'vs/platform/telemetry/common/commonProperties';
import { ITelemetryService, machineIdKey, TelemetryLevel } from 'vs/platform/telemetry/common/telemetry';
import { TelemetryAppenderClient } from 'vs/platform/telemetry/common/telemetryIpc';
import { ITelemetryServiceConfig, TelemetryService } from 'vs/platform/telemetry/common/telemetryService';
import { getPiiPathsFromEnvironment, getTelemetryLevel, NullTelemetryService, supportsTelemetry } from 'vs/platform/telemetry/common/telemetryUtils';
import { IUpdateService } from 'vs/platform/update/common/update';
import { UpdateChannel } from 'vs/platform/update/common/updateIpc';
import { DarwinUpdateService } from 'vs/platform/update/electron-main/updateService.darwin';
import { LinuxUpdateService } from 'vs/platform/update/electron-main/updateService.linux';
import { SnapUpdateService } from 'vs/platform/update/electron-main/updateService.snap';
import { Win32UpdateService } from 'vs/platform/update/electron-main/updateService.win32';
import { IOpenURLOptions, IURLService } from 'vs/platform/url/common/url';
import { URLHandlerChannelClient, URLHandlerRouter } from 'vs/platform/url/common/urlIpc';
import { NativeURLService } from 'vs/platform/url/common/urlService';
import { ElectronURLListener } from 'vs/platform/url/electron-main/electronUrlListener';
import { IWebviewManagerService } from 'vs/platform/webview/common/webviewManagerService';
import { WebviewMainService } from 'vs/platform/webview/electron-main/webviewMainService';
import { IWindowOpenable } from 'vs/platform/window/common/window';
import { IWindowsMainService, OpenContext } from 'vs/platform/windows/electron-main/windows';
import { ICodeWindow, WindowError } from 'vs/platform/window/electron-main/window';
import { WindowsMainService } from 'vs/platform/windows/electron-main/windowsMainService';
import { ActiveWindowManager } from 'vs/platform/windows/node/windowTracker';
import { hasWorkspaceFileExtension } from 'vs/platform/workspace/common/workspace';
import { IWorkspacesService } from 'vs/platform/workspaces/common/workspaces';
import { IWorkspacesHistoryMainService, WorkspacesHistoryMainService } from 'vs/platform/workspaces/electron-main/workspacesHistoryMainService';
import { WorkspacesMainService } from 'vs/platform/workspaces/electron-main/workspacesMainService';
import { IWorkspacesManagementMainService, WorkspacesManagementMainService } from 'vs/platform/workspaces/electron-main/workspacesManagementMainService';
import { CredentialsNativeMainService } from 'vs/platform/credentials/electron-main/credentialsMainService';
import { IPolicyService } from 'vs/platform/policy/common/policy';
import { PolicyChannel } from 'vs/platform/policy/common/policyIpc';

import * as installUtils from 'vs/code/electron-main/installUtils';
import axios from "axios";
// import { Semaphore } from "async-mutex";

import * as fs from 'fs';
import * as path from 'path';
import { spawn, ChildProcess } from 'child_process';
import { AbortController } from "@azure/abort-controller";

/**
 * The main VS Code application. There will only ever be one instance,
 * even if the user starts many instances (e.g. from the command line).
 */
export class CodeApplication extends Disposable {

	private windowsMainService: IWindowsMainService | undefined;
	private nativeHostMainService: INativeHostMainService | undefined;
	private win: BrowserWindow | null = null;
	private baseUrl: string = "";

	constructor(
		private readonly mainProcessNodeIpcServer: NodeIPCServer,
		private readonly userEnv: IProcessEnvironment,
		@IInstantiationService private readonly mainInstantiationService: IInstantiationService,
		@ILogService private readonly logService: ILogService,
		@IEnvironmentMainService private readonly environmentMainService: IEnvironmentMainService,
		@ILifecycleMainService private readonly lifecycleMainService: ILifecycleMainService,
		@IConfigurationService private readonly configurationService: IConfigurationService,
		@IStateMainService private readonly stateMainService: IStateMainService,
		@IFileService private readonly fileService: IFileService,
		@IProductService private readonly productService: IProductService
	) {
		super();

		this.configureSession();
		this.registerListeners();
	}

	private configureSession(): void {

		//#region Security related measures (https://electronjs.org/docs/tutorial/security)
		//
		// !!! DO NOT CHANGE without consulting the documentation !!!
		//

		const isUrlFromWebview = (requestingUrl: string | undefined) => requestingUrl?.startsWith(`${Schemas.vscodeWebview}://`);

		const allowedPermissionsInWebview = new Set([
			'clipboard-read',
			'clipboard-sanitized-write',
		]);

		session.defaultSession.setPermissionRequestHandler((_webContents, permission /* 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal' */, callback, details) => {
			if (isUrlFromWebview(details.requestingUrl)) {
				return callback(allowedPermissionsInWebview.has(permission));
			}

			return callback(false);
		});

		session.defaultSession.setPermissionCheckHandler((_webContents, permission /* 'media' */, _origin, details) => {
			if (isUrlFromWebview(details.requestingUrl)) {
				return allowedPermissionsInWebview.has(permission);
			}

			return false;
		});

		//#endregion

		//#region Request filtering

		// Block all SVG requests from unsupported origins
		const supportedSvgSchemes = new Set([Schemas.file, Schemas.vscodeFileResource, Schemas.vscodeRemoteResource, 'devtools']);

		// But allow them if the are made from inside an webview
		const isSafeFrame = (requestFrame: WebFrameMain | undefined): boolean => {
			for (let frame: WebFrameMain | null | undefined = requestFrame; frame; frame = frame.parent) {
				if (frame.url.startsWith(`${Schemas.vscodeWebview}://`)) {
					return true;
				}
			}
			return false;
		};

		const isSvgRequestFromSafeContext = (details: Electron.OnBeforeRequestListenerDetails | Electron.OnHeadersReceivedListenerDetails): boolean => {
			return details.resourceType === 'xhr' || isSafeFrame(details.frame);
		};

		// const isAllowedVsCodeFileRequest = (details: Electron.OnBeforeRequestListenerDetails) => {
		// 	const frame = details.frame;
		// 	if (!frame || !this.windowsMainService) {
		// 		return false;
		// 	}

		// 	// Check to see if the request comes from one of the main windows (or shared process) and not from embedded content
		// 	const windows = BrowserWindow.getAllWindows();
		// 	for (const window of windows) {
		// 		if (frame.processId === window.webContents.mainFrame.processId) {
		// 			return true;
		// 		}
		// 	}

		// 	return false;
		// };

		const isAllowedWebviewRequest = (uri: URI, details: Electron.OnBeforeRequestListenerDetails): boolean => {
			// Only restrict top level page of webviews: index.html
			if (uri.path !== '/index.html') {
				return true;
			}

			const frame = details.frame;
			if (!frame || !this.windowsMainService) {
				return false;
			}

			// Check to see if the request comes from one of the main editor windows.
			for (const window of this.windowsMainService.getWindows()) {
				if (window.win) {
					if (frame.processId === window.win.webContents.mainFrame.processId) {
						return true;
					}
				}
			}

			return false;
		};

		session.defaultSession.webRequest.onBeforeRequest((details, callback) => {
			const uri = URI.parse(details.url);
			if (uri.scheme === Schemas.vscodeWebview) {
				if (!isAllowedWebviewRequest(uri, details)) {
					this.logService.error('Blocked vscode-webview request', details.url);
					return callback({ cancel: true });
				}
			}

			// if (uri.scheme === Schemas.vscodeFileResource) {
			// 	if (!isAllowedVsCodeFileRequest(details)) {
			// 		this.logService.error('Blocked vscode-file request', details.url);
			// 		return callback({ cancel: true });
			// 	}
			// }

			// Block most svgs
			if (uri.path.endsWith('.svg')) {
				const isSafeResourceUrl = supportedSvgSchemes.has(uri.scheme);
				if (!isSafeResourceUrl) {
					return callback({ cancel: !isSvgRequestFromSafeContext(details) });
				}
			}

			return callback({ cancel: false });
		});

		// Configure SVG header content type properly
		// https://github.com/microsoft/vscode/issues/97564
		session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
			const responseHeaders = details.responseHeaders as Record<string, (string) | (string[])>;
			const contentTypes = (responseHeaders['content-type'] || responseHeaders['Content-Type']);

			if (contentTypes && Array.isArray(contentTypes)) {
				const uri = URI.parse(details.url);
				if (uri.path.endsWith('.svg')) {
					if (supportedSvgSchemes.has(uri.scheme)) {
						responseHeaders['Content-Type'] = ['image/svg+xml'];

						return callback({ cancel: false, responseHeaders });
					}
				}

				// remote extension schemes have the following format
				// http://127.0.0.1:<port>/vscode-remote-resource?path=
				if (!uri.path.endsWith(Schemas.vscodeRemoteResource) && contentTypes.some(contentType => contentType.toLowerCase().includes('image/svg'))) {
					return callback({ cancel: !isSvgRequestFromSafeContext(details) });
				}
			}

			return callback({ cancel: false });
		});

		//#endregion

		//#region Code Cache

		type SessionWithCodeCachePathSupport = Session & {
			/**
			 * Sets code cache directory. By default, the directory will be `Code Cache` under
			 * the respective user data folder.
			 */
			setCodeCachePath?(path: string): void;
		};

		const defaultSession = session.defaultSession as unknown as SessionWithCodeCachePathSupport;
		if (typeof defaultSession.setCodeCachePath === 'function' && this.environmentMainService.codeCachePath) {
			// Make sure to partition Chrome's code cache folder
			// in the same way as our code cache path to help
			// invalidate caches that we know are invalid
			// (https://github.com/microsoft/vscode/issues/120655)
			defaultSession.setCodeCachePath(join(this.environmentMainService.codeCachePath, 'chrome'));
		}

		//#endregion
	}

	private registerListeners(): void {

		// We handle uncaught exceptions here to prevent electron from opening a dialog to the user
		setUnexpectedErrorHandler(error => this.onUnexpectedError(error));
		process.on('uncaughtException', error => onUnexpectedError(error));
		process.on('unhandledRejection', (reason: unknown) => onUnexpectedError(reason));

		// Dispose on shutdown
		this.lifecycleMainService.onWillShutdown(() => this.dispose());

		// Contextmenu via IPC support
		registerContextMenuListener();

		// Accessibility change event
		app.on('accessibility-support-changed', (event, accessibilitySupportEnabled) => {
			this.windowsMainService?.sendToAll('vscode:accessibilitySupportChanged', accessibilitySupportEnabled);
		});

		// macOS dock activate
		app.on('activate', (event, hasVisibleWindows) => {
			this.logService.trace('app#activate');

			// Mac only event: open new window when we get activated
			if (!hasVisibleWindows) {
				this.windowsMainService?.openEmptyWindow({ context: OpenContext.DOCK });
			}
		});

		//#region Security related measures (https://electronjs.org/docs/tutorial/security)
		//
		// !!! DO NOT CHANGE without consulting the documentation !!!
		//
		app.on('web-contents-created', (event, contents) => {

			contents.on('will-navigate', event => {
				this.logService.error('webContents#will-navigate: Prevented webcontent navigation');

				event.preventDefault();
			});

			contents.setWindowOpenHandler(({ url }) => {
				this.nativeHostMainService?.openExternal(undefined, url);

				return { action: 'deny' };
			});
		});

		//#endregion

		let macOpenFileURIs: IWindowOpenable[] = [];
		let runningTimeout: NodeJS.Timeout | undefined = undefined;
		app.on('open-file', (event, path) => {
			this.logService.trace('app#open-file: ', path);
			event.preventDefault();

			// Keep in array because more might come!
			macOpenFileURIs.push(this.getWindowOpenableFromPathSync(path));

			// Clear previous handler if any
			if (runningTimeout !== undefined) {
				clearTimeout(runningTimeout);
				runningTimeout = undefined;
			}

			// Handle paths delayed in case more are coming!
			runningTimeout = setTimeout(() => {
				this.windowsMainService?.open({
					context: OpenContext.DOCK /* can also be opening from finder while app is running */,
					cli: this.environmentMainService.args,
					urisToOpen: macOpenFileURIs,
					gotoLineMode: false,
					preferNewWindow: true /* dropping on the dock or opening from finder prefers to open in a new window */
				});

				macOpenFileURIs = [];
				runningTimeout = undefined;
			}, 100);
		});

		app.on('new-window-for-tab', () => {
			this.windowsMainService?.openEmptyWindow({ context: OpenContext.DESKTOP }); //macOS native tab "+" button
		});

		//#region Bootstrap IPC Handlers

		validatedIpcMain.handle('vscode:fetchShellEnv', event => {

			// Prefer to use the args and env from the target window
			// when resolving the shell env. It is possible that
			// a first window was opened from the UI but a second
			// from the CLI and that has implications for whether to
			// resolve the shell environment or not.
			//
			// Window can be undefined for e.g. the shared process
			// that is not part of our windows registry!
			const window = this.windowsMainService?.getWindowByWebContents(event.sender); // Note: this can be `undefined` for the shared process
			let args: NativeParsedArgs;
			let env: IProcessEnvironment;
			if (window?.config) {
				args = window.config;
				env = { ...process.env, ...window.config.userEnv };
			} else {
				args = this.environmentMainService.args;
				env = process.env;
			}

			// Resolve shell env
			return this.resolveShellEnvironment(args, env, false);
		});

		validatedIpcMain.handle('vscode:writeNlsFile', (event, path: unknown, data: unknown) => {
			const uri = this.validateNlsPath([path]);
			if (!uri || typeof data !== 'string') {
				throw new Error('Invalid operation (vscode:writeNlsFile)');
			}

			return this.fileService.writeFile(uri, VSBuffer.fromString(data));
		});

		validatedIpcMain.handle('vscode:readNlsFile', async (event, ...paths: unknown[]) => {
			const uri = this.validateNlsPath(paths);
			if (!uri) {
				throw new Error('Invalid operation (vscode:readNlsFile)');
			}

			return (await this.fileService.readFile(uri)).value.toString();
		});

		validatedIpcMain.on('vscode:toggleDevTools', event => event.sender.toggleDevTools());
		validatedIpcMain.on('vscode:openDevTools', event => event.sender.openDevTools());

		validatedIpcMain.on('vscode:reloadWindow', event => event.sender.reload());

		//#endregion
		//创建安装引导界面
		ipcMain.on('kylinide.installWizard.openInstallWindow', (event, message) => {
			console.log('kylinide.installWizard.openInstallWindow');
			if (!this.win) {
				this.openInstallWizard(false);
			}
			else {
				this.win.focus();
			}
		});

		//关闭安装引导界面
		ipcMain.on('kylinide.installWizard.closeWizard', (evevt, msg) => {
			if (this.win) {
				this.win.close();
			}
		});

	}

	private validateNlsPath(pathSegments: unknown[]): URI | undefined {
		let path: string | undefined = undefined;

		for (const pathSegment of pathSegments) {
			if (typeof pathSegment === 'string') {
				if (typeof path !== 'string') {
					path = pathSegment;
				} else {
					path = join(path, pathSegment);
				}
			}
		}

		if (typeof path !== 'string' || !isAbsolute(path) || !isEqualOrParent(path, this.environmentMainService.cachedLanguagesPath, !isLinux)) {
			return undefined;
		}

		return URI.file(path);
	}

	private onUnexpectedError(error: Error): void {
		if (error) {

			// take only the message and stack property
			const friendlyError = {
				message: `[uncaught exception in main]: ${error.message}`,
				stack: error.stack
			};

			// handle on client side
			this.windowsMainService?.sendToFocused('vscode:reportError', JSON.stringify(friendlyError));
		}

		this.logService.error(`[uncaught exception in main]: ${error}`);
		if (error.stack) {
			this.logService.error(error.stack);
		}
	}

	async startup(): Promise<void> {
		this.logService.debug('Starting VS Code');
		this.logService.debug(`from: ${this.environmentMainService.appRoot}`);
		this.logService.debug('args:', this.environmentMainService.args);

		// Make sure we associate the program with the app user model id
		// This will help Windows to associate the running program with
		// any shortcut that is pinned to the taskbar and prevent showing
		// two icons in the taskbar for the same app.
		const win32AppUserModelId = this.productService.win32AppUserModelId;
		if (isWindows && win32AppUserModelId) {
			app.setAppUserModelId(win32AppUserModelId);
		}

		// Fix native tabs on macOS 10.13
		// macOS enables a compatibility patch for any bundle ID beginning with
		// "com.microsoft.", which breaks native tabs for VS Code when using this
		// identifier (from the official build).
		// Explicitly opt out of the patch here before creating any windows.
		// See: https://github.com/microsoft/vscode/issues/35361#issuecomment-399794085
		try {
			if (isMacintosh && this.configurationService.getValue('window.nativeTabs') === true && !systemPreferences.getUserDefault('NSUseImprovedLayoutPass', 'boolean')) {
				systemPreferences.setUserDefault('NSUseImprovedLayoutPass', 'boolean', true as any);
			}
		} catch (error) {
			this.logService.error(error);
		}

		// Main process server (electron IPC based)
		const mainProcessElectronServer = new ElectronIPCServer();
		this.lifecycleMainService.onWillShutdown(e => {
			if (e.reason === ShutdownReason.KILL) {
				// When we go down abnormally, make sure to free up
				// any IPC we accept from other windows to reduce
				// the chance of doing work after we go down. Kill
				// is special in that it does not orderly shutdown
				// windows.
				mainProcessElectronServer.dispose();
			}
		});

		// Resolve unique machine ID
		this.logService.trace('Resolving machine identifier...');
		const machineId = await this.resolveMachineId();
		this.logService.trace(`Resolved machine identifier: ${machineId}`);

		// Shared process
		const { sharedProcess, sharedProcessReady, sharedProcessClient } = this.setupSharedProcess(machineId);

		// Services
		const appInstantiationService = await this.initServices(machineId, sharedProcess, sharedProcessReady);

		// Setup Auth Handler
		this._register(appInstantiationService.createInstance(ProxyAuthHandler));

		//install Wizard
		if (await this.isFirstLoad()) {
			await this.openInstallWizard(true);
		}

		// Init Channels
		appInstantiationService.invokeFunction(accessor => this.initChannels(accessor, mainProcessElectronServer, sharedProcessClient));

		// Open Windows
		const windows = appInstantiationService.invokeFunction(accessor => this.openFirstWindow(accessor, mainProcessElectronServer));

		// Post Open Windows Tasks
		appInstantiationService.invokeFunction(accessor => this.afterWindowOpen(accessor, sharedProcess));

		// Tracing: Stop tracing after windows are ready if enabled
		if (this.environmentMainService.args.trace) {
			appInstantiationService.invokeFunction(accessor => this.stopTracingEventually(accessor, windows));
		}
	}

	private async resolveMachineId(): Promise<string> {

		// We cache the machineId for faster lookups on startup
		// and resolve it only once initially if not cached or we need to replace the macOS iBridge device
		let machineId = this.stateMainService.getItem<string>(machineIdKey);
		if (!machineId || (isMacintosh && machineId === '6c9d2bc8f91b89624add29c0abeae7fb42bf539fa1cdb2e3e57cd668fa9bcead')) {
			machineId = await getMachineId();

			this.stateMainService.setItem(machineIdKey, machineId);
		}

		return machineId;
	}

	private setupSharedProcess(machineId: string): { sharedProcess: SharedProcess; sharedProcessReady: Promise<MessagePortClient>; sharedProcessClient: Promise<MessagePortClient> } {
		const sharedProcess = this._register(this.mainInstantiationService.createInstance(SharedProcess, machineId, this.userEnv));

		const sharedProcessClient = (async () => {
			this.logService.trace('Main->SharedProcess#connect');

			const port = await sharedProcess.connect();

			this.logService.trace('Main->SharedProcess#connect: connection established');

			return new MessagePortClient(port, 'main');
		})();

		const sharedProcessReady = (async () => {
			await sharedProcess.whenReady();

			return sharedProcessClient;
		})();

		return { sharedProcess, sharedProcessReady, sharedProcessClient };
	}

	private async initServices(machineId: string, sharedProcess: SharedProcess, sharedProcessReady: Promise<MessagePortClient>): Promise<IInstantiationService> {
		const services = new ServiceCollection();

		// Update
		switch (process.platform) {
			case 'win32':
				services.set(IUpdateService, new SyncDescriptor(Win32UpdateService));
				break;

			case 'linux':
				if (isLinuxSnap) {
					services.set(IUpdateService, new SyncDescriptor(SnapUpdateService, [process.env['SNAP'], process.env['SNAP_REVISION']]));
				} else {
					services.set(IUpdateService, new SyncDescriptor(LinuxUpdateService));
				}
				break;

			case 'darwin':
				services.set(IUpdateService, new SyncDescriptor(DarwinUpdateService));
				break;
		}

		// Windows
		services.set(IWindowsMainService, new SyncDescriptor(WindowsMainService, [machineId, this.userEnv]));

		// Dialogs
		services.set(IDialogMainService, new SyncDescriptor(DialogMainService));

		// Launch
		services.set(ILaunchMainService, new SyncDescriptor(LaunchMainService));

		// Diagnostics
		services.set(IDiagnosticsMainService, new SyncDescriptor(DiagnosticsMainService));
		services.set(IDiagnosticsService, ProxyChannel.toService(getDelayedChannel(sharedProcessReady.then(client => client.getChannel('diagnostics')))));

		// Issues
		services.set(IIssueMainService, new SyncDescriptor(IssueMainService, [this.userEnv]));

		// Encryption
		services.set(IEncryptionMainService, new SyncDescriptor(EncryptionMainService, [machineId]));

		// Keyboard Layout
		services.set(IKeyboardLayoutMainService, new SyncDescriptor(KeyboardLayoutMainService));

		// Native Host
		services.set(INativeHostMainService, new SyncDescriptor(NativeHostMainService, [sharedProcess]));

		// Credentials
		services.set(ICredentialsMainService, new SyncDescriptor(CredentialsNativeMainService));

		// Webview Manager
		services.set(IWebviewManagerService, new SyncDescriptor(WebviewMainService));

		// Workspaces
		services.set(IWorkspacesService, new SyncDescriptor(WorkspacesMainService));
		services.set(IWorkspacesManagementMainService, new SyncDescriptor(WorkspacesManagementMainService));
		services.set(IWorkspacesHistoryMainService, new SyncDescriptor(WorkspacesHistoryMainService));

		// Menubar
		services.set(IMenubarMainService, new SyncDescriptor(MenubarMainService));

		// Extension URL Trust
		services.set(IExtensionUrlTrustService, new SyncDescriptor(ExtensionUrlTrustService));

		// Extension Host Starter
		services.set(IExtensionHostStarter, new SyncDescriptor(ExtensionHostStarter));

		// Storage
		services.set(IStorageMainService, new SyncDescriptor(StorageMainService));
		services.set(IGlobalStorageMainService, new SyncDescriptor(GlobalStorageMainService));

		// External terminal
		if (isWindows) {
			services.set(IExternalTerminalMainService, new SyncDescriptor(WindowsExternalTerminalService));
		} else if (isMacintosh) {
			services.set(IExternalTerminalMainService, new SyncDescriptor(MacExternalTerminalService));
		} else if (isLinux) {
			services.set(IExternalTerminalMainService, new SyncDescriptor(LinuxExternalTerminalService));
		}

		// Backups
		const backupMainService = new BackupMainService(this.environmentMainService, this.configurationService, this.logService);
		services.set(IBackupMainService, backupMainService);

		// URL handling
		services.set(IURLService, new SyncDescriptor(NativeURLService));

		// Telemetry
		if (supportsTelemetry(this.productService, this.environmentMainService)) {
			const channel = getDelayedChannel(sharedProcessReady.then(client => client.getChannel('telemetryAppender')));
			const appender = new TelemetryAppenderClient(channel);
			const commonProperties = resolveCommonProperties(this.fileService, release(), hostname(), process.arch, this.productService.commit, this.productService.version, machineId, this.productService.msftInternalDomains, this.environmentMainService.installSourcePath);
			const piiPaths = getPiiPathsFromEnvironment(this.environmentMainService);
			const config: ITelemetryServiceConfig = { appenders: [appender], commonProperties, piiPaths, sendErrorTelemetry: true };

			services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config]));
		} else {
			services.set(ITelemetryService, NullTelemetryService);
		}

		// Init services that require it
		await backupMainService.initialize();

		return this.mainInstantiationService.createChild(services);
	}

	private initChannels(accessor: ServicesAccessor, mainProcessElectronServer: ElectronIPCServer, sharedProcessClient: Promise<MessagePortClient>): void {

		// Channels registered to node.js are exposed to second instances
		// launching because that is the only way the second instance
		// can talk to the first instance. Electron IPC does not work
		// across apps until `requestSingleInstance` APIs are adopted.

		const launchChannel = ProxyChannel.fromService(accessor.get(ILaunchMainService), { disableMarshalling: true });
		this.mainProcessNodeIpcServer.registerChannel('launch', launchChannel);

		const diagnosticsChannel = ProxyChannel.fromService(accessor.get(IDiagnosticsMainService), { disableMarshalling: true });
		this.mainProcessNodeIpcServer.registerChannel('diagnostics', diagnosticsChannel);

		// Policies (main & shared process)
		const policyChannel = new PolicyChannel(accessor.get(IPolicyService));
		mainProcessElectronServer.registerChannel('policy', policyChannel);
		sharedProcessClient.then(client => client.registerChannel('policy', policyChannel));

		// Local Files
		const diskFileSystemProvider = this.fileService.getProvider(Schemas.file);
		assertType(diskFileSystemProvider instanceof DiskFileSystemProvider);
		const fileSystemProviderChannel = new DiskFileSystemProviderChannel(diskFileSystemProvider, this.logService, this.environmentMainService);
		mainProcessElectronServer.registerChannel(LOCAL_FILE_SYSTEM_CHANNEL_NAME, fileSystemProviderChannel);
		sharedProcessClient.then(client => client.registerChannel(LOCAL_FILE_SYSTEM_CHANNEL_NAME, fileSystemProviderChannel));

		// Update
		const updateChannel = new UpdateChannel(accessor.get(IUpdateService));
		mainProcessElectronServer.registerChannel('update', updateChannel);

		// Issues
		const issueChannel = ProxyChannel.fromService(accessor.get(IIssueMainService));
		mainProcessElectronServer.registerChannel('issue', issueChannel);

		// Encryption
		const encryptionChannel = ProxyChannel.fromService(accessor.get(IEncryptionMainService));
		mainProcessElectronServer.registerChannel('encryption', encryptionChannel);

		// Credentials
		const credentialsChannel = ProxyChannel.fromService(accessor.get(ICredentialsMainService));
		mainProcessElectronServer.registerChannel('credentials', credentialsChannel);

		// Signing
		const signChannel = ProxyChannel.fromService(accessor.get(ISignService));
		mainProcessElectronServer.registerChannel('sign', signChannel);

		// Keyboard Layout
		const keyboardLayoutChannel = ProxyChannel.fromService(accessor.get(IKeyboardLayoutMainService));
		mainProcessElectronServer.registerChannel('keyboardLayout', keyboardLayoutChannel);

		// Native host (main & shared process)
		this.nativeHostMainService = accessor.get(INativeHostMainService);
		const nativeHostChannel = ProxyChannel.fromService(this.nativeHostMainService);
		mainProcessElectronServer.registerChannel('nativeHost', nativeHostChannel);
		sharedProcessClient.then(client => client.registerChannel('nativeHost', nativeHostChannel));

		// Workspaces
		const workspacesChannel = ProxyChannel.fromService(accessor.get(IWorkspacesService));
		mainProcessElectronServer.registerChannel('workspaces', workspacesChannel);

		// Menubar
		const menubarChannel = ProxyChannel.fromService(accessor.get(IMenubarMainService));
		mainProcessElectronServer.registerChannel('menubar', menubarChannel);

		// URL handling
		const urlChannel = ProxyChannel.fromService(accessor.get(IURLService));
		mainProcessElectronServer.registerChannel('url', urlChannel);

		// Extension URL Trust
		const extensionUrlTrustChannel = ProxyChannel.fromService(accessor.get(IExtensionUrlTrustService));
		mainProcessElectronServer.registerChannel('extensionUrlTrust', extensionUrlTrustChannel);

		// Webview Manager
		const webviewChannel = ProxyChannel.fromService(accessor.get(IWebviewManagerService));
		mainProcessElectronServer.registerChannel('webview', webviewChannel);

		// Storage (main & shared process)
		const storageChannel = this._register(new StorageDatabaseChannel(this.logService, accessor.get(IStorageMainService)));
		mainProcessElectronServer.registerChannel('storage', storageChannel);
		sharedProcessClient.then(client => client.registerChannel('storage', storageChannel));

		// External Terminal
		const externalTerminalChannel = ProxyChannel.fromService(accessor.get(IExternalTerminalMainService));
		mainProcessElectronServer.registerChannel('externalTerminal', externalTerminalChannel);

		// Log Level (main & shared process)
		const logLevelChannel = new LogLevelChannel(accessor.get(ILogService));
		mainProcessElectronServer.registerChannel('logLevel', logLevelChannel);
		sharedProcessClient.then(client => client.registerChannel('logLevel', logLevelChannel));

		// Logger
		const loggerChannel = new LoggerChannel(accessor.get(ILoggerService),);
		mainProcessElectronServer.registerChannel('logger', loggerChannel);
		sharedProcessClient.then(client => client.registerChannel('logger', loggerChannel));

		// Extension Host Debug Broadcasting
		const electronExtensionHostDebugBroadcastChannel = new ElectronExtensionHostDebugBroadcastChannel(accessor.get(IWindowsMainService));
		mainProcessElectronServer.registerChannel('extensionhostdebugservice', electronExtensionHostDebugBroadcastChannel);

		// Extension Host Starter
		const extensionHostStarterChannel = ProxyChannel.fromService(accessor.get(IExtensionHostStarter));
		mainProcessElectronServer.registerChannel(ipcExtensionHostStarterChannelName, extensionHostStarterChannel);
	}

	private openFirstWindow(accessor: ServicesAccessor, mainProcessElectronServer: ElectronIPCServer): ICodeWindow[] {
		const windowsMainService = this.windowsMainService = accessor.get(IWindowsMainService);
		const urlService = accessor.get(IURLService);
		const nativeHostMainService = accessor.get(INativeHostMainService);

		// Signal phase: ready (services set)
		this.lifecycleMainService.phase = LifecycleMainPhase.Ready;

		// Check for initial URLs to handle from protocol link invocations
		const pendingWindowOpenablesFromProtocolLinks: IWindowOpenable[] = [];
		const pendingProtocolLinksToHandle = [

			// Windows/Linux: protocol handler invokes CLI with --open-url
			...this.environmentMainService.args['open-url'] ? this.environmentMainService.args._urls || [] : [],

			// macOS: open-url events
			...((<any>global).getOpenUrls() || []) as string[]

		].map(url => {
			try {
				return { uri: URI.parse(url), url };
			} catch {
				return undefined;
			}
		}).filter((obj): obj is { uri: URI; url: string } => {
			if (!obj) {
				return false;
			}

			// If URI should be blocked, filter it out
			if (this.shouldBlockURI(obj.uri)) {
				return false;
			}

			// Filter out any protocol link that wants to open as window so that
			// we open the right set of windows on startup and not restore the
			// previous workspace too.
			const windowOpenable = this.getWindowOpenableFromProtocolLink(obj.uri);
			if (windowOpenable) {
				pendingWindowOpenablesFromProtocolLinks.push(windowOpenable);

				return false;
			}

			return true;
		});

		// Create a URL handler to open file URIs in the active window
		// or open new windows. The URL handler will be invoked from
		// protocol invocations outside of VSCode.
		const app = this;
		const environmentService = this.environmentMainService;
		const productService = this.productService;
		const logService = this.logService;
		urlService.registerHandler({
			async handleURL(uri: URI, options?: IOpenURLOptions): Promise<boolean> {
				logService.trace('app#handleURL: ', uri.toString(true), options);

				if (uri.scheme === productService.urlProtocol && uri.path === 'workspace') {
					uri = uri.with({
						authority: 'file',
						path: URI.parse(uri.query).path,
						query: ''
					});
				}

				// If URI should be blocked, behave as if it's handled
				if (app.shouldBlockURI(uri)) {
					return true;
				}

				let shouldOpenInNewWindow = false;

				// We should handle the URI in a new window if the URL contains `windowId=_blank`
				const params = new URLSearchParams(uri.query);
				if (params.get('windowId') === '_blank') {
					params.delete('windowId');
					uri = uri.with({ query: params.toString() });
					shouldOpenInNewWindow = true;
				}

				// or if no window is open (macOS only)
				shouldOpenInNewWindow ||= isMacintosh && windowsMainService.getWindowCount() === 0;

				// Check for URIs to open in window
				const windowOpenableFromProtocolLink = app.getWindowOpenableFromProtocolLink(uri);
				logService.trace('app#handleURL: windowOpenableFromProtocolLink = ', windowOpenableFromProtocolLink);
				if (windowOpenableFromProtocolLink) {
					const [window] = windowsMainService.open({
						context: OpenContext.API,
						cli: { ...environmentService.args },
						urisToOpen: [windowOpenableFromProtocolLink],
						forceNewWindow: shouldOpenInNewWindow,
						gotoLineMode: true
						// remoteAuthority: will be determined based on windowOpenableFromProtocolLink
					});

					window.focus(); // this should help ensuring that the right window gets focus when multiple are opened

					return true;
				}

				if (shouldOpenInNewWindow) {
					const [window] = windowsMainService.open({
						context: OpenContext.API,
						cli: { ...environmentService.args },
						forceNewWindow: true,
						forceEmpty: true,
						gotoLineMode: true,
						remoteAuthority: getRemoteAuthority(uri)
					});

					await window.ready();

					return urlService.open(uri, options);
				}

				return false;
			}
		});

		// Create a URL handler which forwards to the last active window
		const activeWindowManager = this._register(new ActiveWindowManager({
			onDidOpenWindow: nativeHostMainService.onDidOpenWindow,
			onDidFocusWindow: nativeHostMainService.onDidFocusWindow,
			getActiveWindowId: () => nativeHostMainService.getActiveWindowId(-1)
		}));
		const activeWindowRouter = new StaticRouter(ctx => activeWindowManager.getActiveClientId().then(id => ctx === id));
		const urlHandlerRouter = new URLHandlerRouter(activeWindowRouter);
		const urlHandlerChannel = mainProcessElectronServer.getChannel('urlHandler', urlHandlerRouter);
		urlService.registerHandler(new URLHandlerChannelClient(urlHandlerChannel));

		// Watch Electron URLs and forward them to the UrlService
		this._register(new ElectronURLListener(pendingProtocolLinksToHandle, urlService, windowsMainService, this.environmentMainService, this.productService));

		// Open our first window
		const args = this.environmentMainService.args;
		const macOpenFiles: string[] = (<any>global).macOpenFiles;
		const context = isLaunchedFromCli(process.env) ? OpenContext.CLI : OpenContext.DESKTOP;
		const hasCliArgs = args._.length;
		const hasFolderURIs = !!args['folder-uri'];
		const hasFileURIs = !!args['file-uri'];
		const noRecentEntry = args['skip-add-to-recently-opened'] === true;
		const waitMarkerFileURI = args.wait && args.waitMarkerFilePath ? URI.file(args.waitMarkerFilePath) : undefined;
		const remoteAuthority = args.remote || undefined;

		// check for a pending window to open from URI
		// e.g. when running code with --open-uri from
		// a protocol handler
		if (pendingWindowOpenablesFromProtocolLinks.length > 0) {
			return windowsMainService.open({
				context,
				cli: args,
				urisToOpen: pendingWindowOpenablesFromProtocolLinks,
				gotoLineMode: true,
				initialStartup: true
				// remoteAuthority: will be determined based on pendingWindowOpenablesFromProtocolLinks
			});
		}

		// new window if "-n"
		if (args['new-window'] && !hasCliArgs && !hasFolderURIs && !hasFileURIs) {
			return windowsMainService.open({
				context,
				cli: args,
				forceNewWindow: true,
				forceEmpty: true,
				noRecentEntry,
				waitMarkerFileURI,
				initialStartup: true,
				remoteAuthority
			});
		}

		// mac: open-file event received on startup
		if (macOpenFiles.length && !hasCliArgs && !hasFolderURIs && !hasFileURIs) {
			return windowsMainService.open({
				context: OpenContext.DOCK,
				cli: args,
				urisToOpen: macOpenFiles.map(file => this.getWindowOpenableFromPathSync(file)),
				noRecentEntry,
				waitMarkerFileURI,
				initialStartup: true,
				// remoteAuthority: will be determined based on macOpenFiles
			});
		}

		// default: read paths from cli
		return windowsMainService.open({
			context,
			cli: args,
			forceNewWindow: args['new-window'] || (!hasCliArgs && args['unity-launch']),
			diffMode: args.diff,
			noRecentEntry,
			waitMarkerFileURI,
			gotoLineMode: args.goto,
			initialStartup: true,
			remoteAuthority
		});
	}

	private shouldBlockURI(uri: URI): boolean {
		if (uri.authority === Schemas.file && isWindows) {
			const res = dialog.showMessageBoxSync({
				title: this.productService.nameLong,
				type: 'question',
				buttons: [
					mnemonicButtonLabel(localize({ key: 'open', comment: ['&& denotes a mnemonic'] }, "&&Yes")),
					mnemonicButtonLabel(localize({ key: 'cancel', comment: ['&& denotes a mnemonic'] }, "&&No")),
				],
				defaultId: 0,
				cancelId: 1,
				message: localize('confirmOpenMessage', "An external application wants to open '{0}' in {1}. Do you want to open this file or folder?", getPathLabel(uri, { os: OS, tildify: this.environmentMainService }), this.productService.nameShort),
				detail: localize('confirmOpenDetail', "If you did not initiate this request, it may represent an attempted attack on your system. Unless you took an explicit action to initiate this request, you should press 'No'"),
				noLink: true
			});

			if (res === 1) {
				return true;
			}
		}

		return false;
	}

	private getWindowOpenableFromProtocolLink(uri: URI): IWindowOpenable | undefined {
		if (!uri.path) {
			return undefined;
		}

		// File path
		if (uri.authority === Schemas.file) {
			const fileUri = URI.file(uri.fsPath);

			if (hasWorkspaceFileExtension(fileUri)) {
				return { workspaceUri: fileUri };
			}

			return { fileUri };
		}

		// Remote path
		else if (uri.authority === Schemas.vscodeRemote) {
			// Example conversion:
			// From: vscode://vscode-remote/wsl+ubuntu/mnt/c/GitDevelopment/monaco
			//   To: vscode-remote://wsl+ubuntu/mnt/c/GitDevelopment/monaco
			const secondSlash = uri.path.indexOf(posix.sep, 1 /* skip over the leading slash */);
			if (secondSlash !== -1) {
				const authority = uri.path.substring(1, secondSlash);
				const path = uri.path.substring(secondSlash);
				const remoteUri = URI.from({ scheme: Schemas.vscodeRemote, authority, path, query: uri.query, fragment: uri.fragment });

				if (hasWorkspaceFileExtension(path)) {
					return { workspaceUri: remoteUri };
				}

				if (/:[\d]+$/.test(path)) {
					// path with :line:column syntax
					return { fileUri: remoteUri };
				}

				return { folderUri: remoteUri };
			}
		}

		return undefined;
	}

	private getWindowOpenableFromPathSync(path: string): IWindowOpenable {
		try {
			const fileStat = statSync(path);
			if (fileStat.isDirectory()) {
				return { folderUri: URI.file(path) };
			}

			if (hasWorkspaceFileExtension(path)) {
				return { workspaceUri: URI.file(path) };
			}
		} catch (error) {
			// ignore errors
		}

		return { fileUri: URI.file(path) };
	}

	private async afterWindowOpen(accessor: ServicesAccessor, sharedProcess: SharedProcess): Promise<void> {

		// Signal phase: after window open
		this.lifecycleMainService.phase = LifecycleMainPhase.AfterWindowOpen;

		// Observe shared process for errors
		let willShutdown = false;
		once(this.lifecycleMainService.onWillShutdown)(() => willShutdown = true);
		const telemetryService = accessor.get(ITelemetryService);
		this._register(sharedProcess.onDidError(({ type, details }) => {

			// Logging
			let message: string;
			switch (type) {
				case WindowError.UNRESPONSIVE:
					message = 'SharedProcess: detected unresponsive window';
					break;
				case WindowError.CRASHED:
					message = `SharedProcess: crashed (detail: ${details?.reason ?? '<unknown>'}, code: ${details?.exitCode ?? '<unknown>'})`;
					break;
				case WindowError.LOAD:
					message = `SharedProcess: failed to load (detail: ${details?.reason ?? '<unknown>'}, code: ${details?.exitCode ?? '<unknown>'})`;
					break;
			}
			onUnexpectedError(new Error(message));

			// Telemetry
			type SharedProcessErrorClassification = {
				type: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'The type of shared process crash to understand the nature of the crash better.' };
				reason: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'The type of shared process crash to understand the nature of the crash better.' };
				code: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'The type of shared process crash to understand the nature of the crash better.' };
				visible: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Whether shared process window was visible or not.' };
				shuttingdown: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Whether the application is shutting down when the crash happens.' };
				owner: 'bpasero';
				comment: 'Event which fires whenever an error occurs in the shared process';

			};
			type SharedProcessErrorEvent = {
				type: WindowError;
				reason: string | undefined;
				code: number | undefined;
				visible: boolean;
				shuttingdown: boolean;
			};
			telemetryService.publicLog2<SharedProcessErrorEvent, SharedProcessErrorClassification>('sharedprocesserror', {
				type,
				reason: details?.reason,
				code: details?.exitCode,
				visible: sharedProcess.isVisible(),
				shuttingdown: willShutdown
			});
		}));

		// Windows: install mutex
		const win32MutexName = this.productService.win32MutexName;
		if (isWindows && win32MutexName) {
			try {
				const WindowsMutex = (require.__$__nodeRequire('windows-mutex') as typeof import('windows-mutex')).Mutex;
				const mutex = new WindowsMutex(win32MutexName);
				once(this.lifecycleMainService.onWillShutdown)(() => mutex.release());
			} catch (error) {
				this.logService.error(error);
			}
		}

		// Remote Authorities
		protocol.registerHttpProtocol(Schemas.vscodeRemoteResource, (request, callback) => {
			callback({
				url: request.url.replace(/^vscode-remote-resource:/, 'http:'),
				method: request.method
			});
		});

		// Initialize update service
		const updateService = accessor.get(IUpdateService);
		if (updateService instanceof Win32UpdateService || updateService instanceof LinuxUpdateService || updateService instanceof DarwinUpdateService) {
			updateService.initialize();
		}

		// Start to fetch shell environment (if needed) after window has opened
		// Since this operation can take a long time, we want to warm it up while
		// the window is opening.
		// We also show an error to the user in case this fails.
		this.resolveShellEnvironment(this.environmentMainService.args, process.env, true);

		// If enable-crash-reporter argv is undefined then this is a fresh start,
		// based on telemetry.enableCrashreporter settings, generate a UUID which
		// will be used as crash reporter id and also update the json file.
		try {
			const argvContent = await this.fileService.readFile(this.environmentMainService.argvResource);
			const argvString = argvContent.value.toString();
			const argvJSON = JSON.parse(stripComments(argvString));
			if (argvJSON['enable-crash-reporter'] === undefined) {
				const telemetryLevel = getTelemetryLevel(this.configurationService);
				const enableCrashReporter = telemetryLevel >= TelemetryLevel.CRASH;
				const additionalArgvContent = [
					'',
					'	// Allows to disable crash reporting.',
					'	// Should restart the app if the value is changed.',
					`	"enable-crash-reporter": ${enableCrashReporter},`,
					'',
					'	// Unique id used for correlating crash reports sent from this instance.',
					'	// Do not edit this value.',
					`	"crash-reporter-id": "${generateUuid()}"`,
					'}'
				];
				const newArgvString = argvString.substring(0, argvString.length - 2).concat(',\n', additionalArgvContent.join('\n'));

				await this.fileService.writeFile(this.environmentMainService.argvResource, VSBuffer.fromString(newArgvString));
			}
		} catch (error) {
			this.logService.error(error);
		}
	}

	private async resolveShellEnvironment(args: NativeParsedArgs, env: IProcessEnvironment, notifyOnError: boolean): Promise<typeof process.env> {
		try {
			return await getResolvedShellEnv(this.logService, args, env);
		} catch (error) {
			const errorMessage = toErrorMessage(error);
			if (notifyOnError) {
				this.windowsMainService?.sendToFocused('vscode:showResolveShellEnvError', errorMessage);
			} else {
				this.logService.error(errorMessage);
			}
		}

		return {};
	}

	private stopTracingEventually(accessor: ServicesAccessor, windows: ICodeWindow[]): void {
		this.logService.info('Tracing: waiting for windows to get ready...');

		const dialogMainService = accessor.get(IDialogMainService);

		let recordingStopped = false;
		const stopRecording = async (timeout: boolean) => {
			if (recordingStopped) {
				return;
			}

			recordingStopped = true; // only once

			const path = await contentTracing.stopRecording(`${randomPath(this.environmentMainService.userHome.fsPath, this.productService.applicationName)}.trace.txt`);

			if (!timeout) {
				dialogMainService.showMessageBox({
					title: this.productService.nameLong,
					type: 'info',
					message: localize('trace.message', "Successfully created trace."),
					detail: localize('trace.detail', "Please create an issue and manually attach the following file:\n{0}", path),
					buttons: [mnemonicButtonLabel(localize({ key: 'trace.ok', comment: ['&& denotes a mnemonic'] }, "&&OK"))],
					defaultId: 0,
					noLink: true
				}, withNullAsUndefined(BrowserWindow.getFocusedWindow()));
			} else {
				this.logService.info(`Tracing: data recorded (after 30s timeout) to ${path}`);
			}
		};

		// Wait up to 30s before creating the trace anyways
		const timeoutHandle = setTimeout(() => stopRecording(true), 30000);

		// Wait for all windows to get ready and stop tracing then
		Promise.all(windows.map(window => window.ready())).then(() => {
			clearTimeout(timeoutHandle);
			stopRecording(false);
		});
	}

	private async openInstallWizard(isFirstLoad?: boolean) {
		return new Promise(async (resolve, reject) => {

			installUtils.logger.info("打开安装引导器");
			console.log('start openInstallWizard()');
			//获取主题dark or other
			const theme = this.configurationService.getValue('workbench.colorTheme') ? this.configurationService.getValue('workbench.colorTheme') : 'Visual Studio Dark';
			console.log('get config color theme=' + this.configurationService.getValue('workbench.colorTheme'));
			// 创建浏览器窗口

			this.win = new BrowserWindow({
				resizable: true,
				maxHeight: 600,
				maxWidth: 900,
				minHeight: 450,
				minWidth: 700,
				height: 600,
				width: 900,
				frame: false,
				transparent: false,
				fullscreen: false,
				icon: join(this.environmentMainService.appRoot, 'resources/linux/code.png'),
				webPreferences: {
					nodeIntegration: true,
					nodeIntegrationInSubFrames: true,
					contextIsolation: false,
					nodeIntegrationInWorker: true,
					enableWebSQL: false,
					spellcheck: false,
					images: true,
					webgl: true,
					plugins: true
				}
			});

			//判断配置中的key值，是否设置跳过步骤，如果有，选择跳过
			//载入网页
			const htmlpath = FileAccess.asFileUri('vs/code/electron-main/installWizard/page/view/index.html', require).fsPath;
			this.win.loadFile(htmlpath);

			//关闭菜单栏
			this.win.setMenuBarVisibility(false);
			//打开开发者工具
			// this.win.webContents.openDevTools();

			let that: CodeApplication = this;
			//传入回复数据 TODO
			let restoreData: any;

			//封装发送给渲染进程的数据
			let initData = {
				restoreData: restoreData,
				height: 600,
				width: 900,
				theme: theme,
				userDataPath: that.environmentMainService.userDataPath,
				isBeta: false,
				IDEVersion: this.productService.IDEVersion,
				isFirstLoad: isFirstLoad,
			}

			let installQueue: { installCommand: any; msg: any; }[] = []; // 定义一个消息队列
			let extDownloadPath = '';
			let startInstallDepWatch = 0;
			let extMap: Record<string, string> = {};
			let depList: string[] = [];
			let extList: string[] = [];
			//文件监听；
			let installFsWatcher: fs.FSWatcher | null;
			let extlogFsWatcher: fs.FSWatcher | null;
			let pkglogFsWatcher: fs.FSWatcher | null;
			//执行安装脚本的进程号；
			let installProcessId: ChildProcess;
			let cancelFlag = false;

			let controller = new AbortController();
			// let scriptList: {}[] = [];
			//electron生命周期 监听did-finish-load事件
			this.win.webContents.on('did-finish-load', async function () {
				console.log('openInstallWizard did-finish-load');
				if (that.win) {
					that.win.webContents.send('init-data', initData);
				}
			});

			//electron生命周期 监听did-fail-load事件
			this.win.webContents.on('did-fail-load', (e) => {
				//可发送给渲染页面显示加载页面错误 TODO
				console.log("error" + e)

			});

			////移除监听
			this.win.on('close', (e) => {
				installUtils.logger.info("关闭安装引导器");
				ipcMain.removeAllListeners('kylinide.installWizard.ok');
				ipcMain.removeAllListeners('message-to-jsb');
				ipcMain.removeAllListeners('kylinide.installWizard.getFilePath');
				ipcMain.removeAllListeners('kylinide.installWizard.checkInstall');
				ipcMain.removeAllListeners('kylinide.installWizard.downloadExt');
				ipcMain.removeAllListeners('kylinide.installWizard.msg.process');
				ipcMain.removeAllListeners('kylinide.installWizard.msg');
				ipcMain.removeAllListeners('kylinide.installWizard.cleanDir');
				ipcMain.removeAllListeners('kylinide.installWizard.showErrorBox');
				ipcMain.removeAllListeners('kylinide.installWizard.init');
				ipcMain.removeAllListeners('kylinide.installWizard.justDownLoad');
				ipcMain.removeAllListeners('kylinide.installWizard.removeFileLister');
				ipcMain.removeAllListeners('kylinide.installWizard.show');
				//读取selectfile.json中selecdir的值，如果值不同，则删除当前的时间戳目录
				if (updateConfigDir) {
					console.log("updateConfig:" + updateConfigDir)
					const selectdir = installUtils.localConfigPath();
					if (updateConfigDir !== selectdir)
						if (fs.existsSync(updateConfigDir))
							fs.rmdirSync(updateConfigDir, { recursive: true });
				}
				this.win = null;
				extDownloadPath = '';
				startInstallDepWatch = 0;
				extMap = {};
				depList = [];
				extList = [];
				// scriptList = [];
				installQueue = [];
			});

			//信息提示，错误信息，警告信息
			ipcMain.on('kylinide.installWizard.showErrorBox', (event, arg) => {
				if (arg.type = "internetError")
					if (this.win) {
						dialog.showMessageBox(this.win,
							{
								type: "error",
								title: arg.title,
								message: arg.message
							});
					}

			});
			ipcMain.on('kylinide.installWizard.show', (event, arg) => {
				if (arg.type = "info")
					if (this.win) {
						dialog.showMessageBox(this.win,
							{
								type: "info",
								title: arg.title,
								message: arg.message
							});
					}
			});

			ipcMain.on('message-to-jsb', (event, message) => {
				depList = [];
				extList = [];
				// scriptList = [];
				depList = message.depList;
				extList = message.extList;
				// scriptList = message.scriptList;
				extMap = {};
				if (this.win)
					this.win.webContents.send('message-to-jsb', message);
			});

			//跳过安装引导界面
			ipcMain.on('kylinide.installWizard.ok', async (evevt) => {
				if (this.win && this.win != undefined)
					this.win.close();
				resolve(void 0);
			});

			//渲染进程发送删除文件的命令
			ipcMain.on('kylinide.installWizard.cleanDir', async (event, arg) => {
				if (fs.existsSync(arg.path))
					fs.rmdirSync(arg.path, { recursive: true });
			});

			let localConfigObject: {
				depConfigInfo: any;
				res: any;
				g_index_Object: any;
				osinfo: any;
				localConfigMatch?: number;
			};//本地配置数据{操作系统信息，全局索引配置文件信息}
			let localConfigDir = installUtils.localConfigPath();//存放本地配置的目录
			let installConfig = installUtils.installConfigDirPre();//.kylin-ide/installconfig
			let updateConfigDir: string;//具体带时间戳的下载地址，如果没有更新配置文件，该目录会被清除
			let updateConfigObject: {
				depConfigInfo: any;
				res: any;
				g_index_Object: any;
				osinfo: any;
				ConfigMatch?: number;
				base_url?: any;
			};
			let selectObject = {
				updateFlag: false,
				depInfoJsonPath: "", //选中的依赖配置文件路径，
				extAddressPath: "",//选中的插件配置文件路径
				dirPath: ''
			}

			ipcMain.on('kylinide.installWizard.justDownLoad', async (event, msg) => {
				if (msg.type === "getPath") {
					if (that.win) {

						const result = await dialog.showOpenDialog(that.win, {
							title: "文件选择窗口",
							buttonLabel: '选择文件夹',
							properties: ["openDirectory"]
						});
						console.log(result);
						const filePath = result && result.filePaths && result.filePaths[0] || '';
						// 主进程发送选择的目录到渲染页面中
						that.win.webContents.send('kylinide.installWizard.justDownLoad', { selectPath: filePath, type: "getPath" });
					}
					//wait to do
				}
			});

			ipcMain.on('kylinide.installWizard.init', async (event, msg) => {
				let selectPageShow = 0;
				let message;
				if (msg.type === "configVersify") {
					updateConfigDir = msg.dst;
					installUtils.logger.info("开始校验本地数据");
					localConfigObject = await this.localConfigVerify(localConfigDir, this.productService.IDEVersion);
					installUtils.logger.info("本地数据校验结束");
					installUtils.logger.info("开始下载校验网络数据");
					updateConfigObject = await this.downloadAndVerify(updateConfigDir, msg);
					installUtils.logger.info("网络数据校验结束");
					//1.本地error ,net error  -1;
					//2.本地error,net right 1;
					//3.本地 right ,net error 2;
					//4.本地right ,net right  ,==  3
					//5.本地right ,net right , !=  4
					//for test
					if (localConfigObject.res != 0 && updateConfigObject.res != 0) {
						if (this.win) {
							if (localConfigObject.osinfo == "undefined" && updateConfigObject.osinfo == "undefined") {
								installUtils.logger.error("安装引导器仅支持openKylin操作系统，脚本根据/etc/os-release信息判断操作系统类型");
								dialog.showMessageBox(this.win,
									{
										type: "error",
										title: "配置文件检查",
										buttons: ["OK"],
										detail: `点击【OK】按钮后，将跳过此引导步骤，请根据开发需要自行下载插件、安装软件依赖。具体信息请查看日志${installConfig}/log/instguide.log`,
										message: "安装引导器不支持当前系统。"
									}).then(result => {
										if (this.win && this.win != undefined)
											this.win.close();
										resolve(void 0);
									})
							} else {
								installUtils.logger.error("本地数据及网络数据校验失败");
								dialog.showMessageBox(this.win,
									{
										type: "error",
										title: "配置文件检查",
										buttons: ["OK"],
										detail: `点击【OK】按钮后，将跳过此引导步骤，请根据开发需要自行下载插件、安装软件依赖。具体信息请查看日志${installConfig}/log/instguide.log`,
										message: "本地数据及网络数据校验失败"
									}).then(result => {
										if (this.win && this.win != undefined)
											this.win.close();
										resolve(void 0);
									})
							}

						}
						selectPageShow = -1;
					} else {

						if (localConfigObject.res != 0 && updateConfigObject.res == 0) {

							selectPageShow = 1;
							if (localConfigObject.osinfo == "undefined") {
								message = "本地配置文件不支持当前环境，选择更新选项";
								installUtils.logger.error(message);
							} else {
								message = "本地配置文件已损坏，选择更新选项";
								installUtils.logger.error("本地数据校验失败");
							}

						} else if (localConfigObject.res == 0 && updateConfigObject.res != 0) {
							if (updateConfigObject.osinfo == "undefined") {
								message = "联网数据文件不支持当前环境";
								installUtils.logger.error(message);
							} else {
								message = "网络数据文件校验失败";
								installUtils.logger.error(message);
							}
							selectPageShow = 2;
						} else if (localConfigObject.res == 0 && updateConfigObject.res == 0) {
							if (installUtils.compareVersions(updateConfigObject.g_index_Object.ver, localConfigObject.g_index_Object.ver) > 0) {
								//显示询问用户是否更新配置文件
								//比较具体的配置文件是否一致，若是一致则还是选择本地配置，若是不同则
								let updateosinfo = updateConfigObject.osinfo;
								let localosinfo = localConfigObject.osinfo;
								if (updateConfigObject.g_index_Object["config-file"][updateosinfo][0]['sign-md5'] !== localConfigObject.g_index_Object["config-file"][localosinfo][0]['sign-md5'])
									selectPageShow = 4;
								else {
									installUtils.logger.info("联网数据与本地配置文件数据版本一致");
									selectPageShow = 3;
									message = "联网数据与本地配置文件数据版本一致";
								}
							} else {
								selectPageShow = 3;
								installUtils.logger.info("联网数据与本地配置文件数据版本一致");
								message = "联网数据与本地配置文件数据版本一致";
							}
						}
						console.log("selectPageShow:" + selectPageShow);
						let Data;
						if (selectPageShow == 0) {
							selectObject.depInfoJsonPath = localConfigDir + "/" + localConfigObject.depConfigInfo['file_name'];
							selectObject.extAddressPath = localConfigDir + "/" + localConfigObject.g_index_Object['ext-file']['file_name'];
							Data = {
								osinfo: localConfigObject.osinfo,
								selectPageShow: selectPageShow,
								type: "configVersify"
							}

						} else {
							Data = {
								localConfigObject: localConfigObject,
								updateConfigObject: updateConfigObject,
								selectPageShow: selectPageShow,
								message: message,
								type: "configVersify"
							}
						}
						if (that.win) {
							that.win.webContents.send('kylinide.installWizard.init', Data);
						}
					}
					//联网下载、检查、校验配置
				} else if (msg.type === "configSelect") {
					let osinfo = "";
					if (msg.select === "local") {
						osinfo = localConfigObject.osinfo;
						selectObject.dirPath = localConfigDir;
						selectObject.updateFlag = false;
						selectObject.depInfoJsonPath = localConfigDir + "/" + localConfigObject.depConfigInfo['file_name'];
						selectObject.extAddressPath = localConfigDir + "/" + localConfigObject.g_index_Object['ext-file']['file_name'];
					} else if (msg.select === "update") {
						selectObject.dirPath = updateConfigDir;
						selectObject.updateFlag = true;
						osinfo = updateConfigObject.osinfo;
						selectObject.depInfoJsonPath = updateConfigDir + "/" + updateConfigObject.depConfigInfo['file_name'];
						selectObject.extAddressPath = updateConfigDir + "/" + updateConfigObject.g_index_Object['ext-file']['file_name']; //error

					}
					const Data = {
						type: "osinfo",
						osinfo: osinfo
					}
					if (that.win) {
						that.win.webContents.send('kylinide.installWizard.init', Data);
					}
					installUtils.logger.info(`选择的配置文件名称：${selectObject.depInfoJsonPath}`);
					installUtils.logger.info(`识别操作系统信息：${osinfo}`);
				} else if (msg.type === "configGetValue") {
					const selectJson = installUtils.selectFileJson();
					let selectKey: string[];
					if (selectJson && selectJson.hasOwnProperty('selectKey'))
						selectKey = selectJson['selectKey'];
					else { selectKey = []; }
					const Data = {
						type: "configGetValue",
						depInfoJsonPath: selectObject.depInfoJsonPath,
						extAddressPath: selectObject.extAddressPath,
						selectKey: selectKey ? selectKey : []
					}
					if (that.win) {
						that.win.webContents.send('kylinide.installWizard.init', Data);
					}
				} else if (msg.type === "writeJson") {
					if (selectObject.updateFlag) {
						installUtils.modifyJsonProperty(installConfig + "/" + "selectFile.json", "selectDir", updateConfigDir);
					} else {
						installUtils.modifyJsonProperty(installConfig + "/" + "selectFile.json", "selectDir", localConfigDir);
					}
				} else if (msg.type === 'writeKey') {
					installUtils.modifyJsonProperty(installConfig + "/" + "selectFile.json", "selectKey", msg.keys);
				}



			});
			let lastLogPosition = 0;
			let lastExtLogPosition = 0;
			const maxBackupFiles = 7;
			const logFile0 = installConfig + '/log/install.1.log';
			const resultFile = installConfig + '/resultFile';
			const extLogFile0 = installConfig + '/log/extInstall.1.log';

			// 获取备份文件名
			function getBackupFileName(filePath: string, index: number) {
				const path = require('path');
				const extname = path.extname(filePath);
				const basename = path.basename(filePath, extname);
				return `${basename}.${index}${extname}`;
			}

			// 备份日志文件
			function backupLogFile(filePath: string) {
				const path = require('path');
				for (let i = maxBackupFiles - 1; i >= 0; i--) {
					const currentFileName = i === 0 ? filePath : getBackupFileName(filePath, i);
					const nextFileName = getBackupFileName(filePath, i + 1);
					const currentFilePath = path.join(path.dirname(filePath), currentFileName);
					const nextFilePath = path.join(path.dirname(filePath), nextFileName);

					if (fs.existsSync(currentFilePath)) {
						if (i === maxBackupFiles - 1) {
							if (fs.existsSync(nextFileName))
								fs.unlinkSync(nextFilePath);
						}
						fs.copyFileSync(currentFilePath, nextFilePath);
					}
				}
			}
			//检查软件包安装进度
			let offset = 0;
			let resultIndex = 0;
			ipcMain.on('kylinide.installWizard.checkInstall', async (event, args) => {
				console.log("kylinide.installWizard.checkInstall");
				if (startInstallDepWatch === 1) return;
				lastLogPosition = 0;
				lastExtLogPosition = 0;
				if (!fs.existsSync(logFile0)) {
					fs.mkdirSync(installConfig, { recursive: true });
					fs.writeFileSync(logFile0, '');
				}
				//监听install pkg输出信息
				pkglogFsWatcher =
					fs.watch(logFile0, (eventType, filename) => {
						if (eventType === 'change') {
							// 获取文件的当前大小
							const stats = fs.statSync(logFile0);
							const currentSize = stats.size;
							if (lastLogPosition === 0 && stats.size > 0) {
								const startDownloadExtMsg = {
									type: "extDownloadInit",
								}
								if (that.win)
									that.win.webContents.send("kylinide.installWizard.msg", startDownloadExtMsg)

								const extlogFile0 = installConfig + '/log/extInstall.1.log';
								fs.writeFileSync(extlogFile0, '');
							}

							// 计算更新部分的大小
							const updateSize = currentSize - lastLogPosition;
							if (updateSize <= 0) return;

							// 读取更新部分的内容
							const buffer = Buffer.alloc(updateSize);
							const fileDescriptor = fs.openSync(logFile0, 'r');
							fs.readSync(fileDescriptor, buffer, 0, updateSize, lastLogPosition);
							fs.closeSync(fileDescriptor);

							// 将更新部分的内容转换为字符串并输出
							const updatedContent = buffer.toString('utf8');

							// 更新上一次读取的位置
							lastLogPosition = currentSize;
							const installMsg = {
								type: "installLogPre",
								data: updatedContent
							};

							if (that.win)
								that.win.webContents.send("kylinide.installWizard.msg", installMsg);
						}

					});

				//检测ext 安装信息文件变化
				extlogFsWatcher =
					fs.watch(extLogFile0, (eventType, filename) => {
						if (eventType === 'change') {
							// 获取文件的当前大小
							const stats = fs.statSync(extLogFile0);
							const currentSize = stats.size;

							// 计算更新部分的大小
							const updateSize = currentSize - lastExtLogPosition;
							if (updateSize <= 0) return;
							// 读取更新部分的内容
							const buffer = Buffer.alloc(updateSize);
							const fileDescriptor = fs.openSync(extLogFile0, 'r');
							fs.readSync(fileDescriptor, buffer, 0, updateSize, lastExtLogPosition);
							fs.closeSync(fileDescriptor);

							// 将更新部分的内容转换为字符串并输出
							const updatedContent = buffer.toString('utf8');

							// 更新上一次读取的位置
							lastExtLogPosition = currentSize;
							const installMsg = {
								type: "extInstallLogPre",
								data: updatedContent
							};

							if (that.win)
								that.win.webContents.send("kylinide.installWizard.msg", installMsg);
						}
					});

				installFsWatcher = fs.watch(resultFile, (evenType, filename) => {
					if (evenType === "change") {
						fs.readFile(resultFile, "utf8", (err, data) => {
							if (err) {
								console.error(`读取 resultFile 文件时发生错误：${err}`);
								return;
							}
							// 计算文件变化的部分的偏移量
							const newOffset = data.length;

							// 如果文件没有发生变化，直接返回
							if (newOffset === offset) {
								return;
							}

							// 读取文件变化的部分
							const changeData = data.slice(offset);

							// 更新文件偏移量
							offset = newOffset;

							let result = changeData.trim();
							// 处理文件变化的部分
							console.log(`result ${resultIndex + 1} 结果为 ${result} 。`);
							//每个dep的安装状态
							let installMsg;
							if (result === '') {
								//此处是因为每次清零的时候会监听到改变
								console.log(`result ${resultIndex + 1} 结果为空。`);
								resultIndex = 0;
								return;
							} else if (result === '0') {
								installMsg = {
									type: "depInstallSucc",
									depName: depList[resultIndex],
									result: "0",
									succ: resultIndex
								};
								if (that.win)
									that.win.webContents.send("kylinide.installWizard.msg", installMsg);
							} else {
								installMsg = {
									type: "depInstallFail",
									depName: depList[resultIndex],
									result: "0",
									succ: resultIndex //失败
								};
								if (that.win)
									that.win.webContents.send("kylinide.installWizard.msg", installMsg);
							}

							if (resultIndex == depList.length - 1) {
								if (that.win)
									that.win.webContents.send("kylinide.installWizard.removeFileLister", { type: "installFile" });
								resultIndex = 0;
								return;
							}
							resultIndex++;
						});
					}
				});
				startInstallDepWatch = 1;
			});

			ipcMain.on("kylinide.installWizard.removeFileLister", async (event, msg) => {
				if (msg.type == "installFile") {
					if (installFsWatcher) {
						installFsWatcher.close();
						installFsWatcher = null;
					}
				} else if (msg.type == "extFile") {
					if (extlogFsWatcher) {
						extlogFsWatcher.close();
						extlogFsWatcher = null;
					}

				} else if (msg.type == "pkgFile") {
					if (pkglogFsWatcher) {
						pkglogFsWatcher.close();
						pkglogFsWatcher = null;
					}
				}

			});

			ipcMain.on('kylinide.installWizard.downloadExt', async (event, message) => {
				installQueue.splice(0);
				let depObject = JSON.parse(fs.readFileSync(message.extAddressPath, 'utf-8'));
				let extLatestDownloadUrlList = [];
				let extDownloadUrlList = [];
				extDownloadPath = installConfig + '/Download/'

				extList.forEach(async (val) => {
					// await semaphore.acquire(); // 获取信号量，控制并发数量

					let gitInfo = depObject[val]['ext_links']['gitee'];
					let tempUrl = gitInfo.prefix + '/' + gitInfo.org + '/' + gitInfo.repo + '/' + 'releases/latest';
					extLatestDownloadUrlList.push(tempUrl);

					// download extension
					try {
						const response = await axios.get(tempUrl, {
							headers: {
								'User-Agent': 'axios',
								'Accept': '*/*',
							},
							timeout: 10000,
							signal: controller.signal
						});
						const downloadUrl = response.data.release.release.attach_files[0].download_url;
						const downloadUrlAddr = gitInfo.prefix + downloadUrl;
						extDownloadUrlList.push(downloadUrlAddr);
						const start = downloadUrlAddr.lastIndexOf('/') + 1;
						const filename = downloadUrlAddr.slice(start);
						extMap[val] = filename;

						const startDownloadMsg = {
							type: 'extStartDownload',
							extName: val,
							extMap: extMap,
							// extTotal: extMap.length,
							extTotal: extList.length,
						};
						if (that.win) that.win.webContents.send('kylinide.installWizard.msg', startDownloadMsg);
						if (!cancelFlag) {
							this.download_File(downloadUrlAddr, extDownloadPath + filename, controller).then((result) => {
								const msg = {
									type: 'downloadExtDone',
									fileName: filename,
									extName: val,
									extMap: extMap,
									extTotal: Object.keys(extMap).length,
								};
								if (result === 0) {
									if (that.win) that.win.webContents.send('kylinide.installWizard.msg', msg);
								} else {
									console.log(`Download ${val} failed0: `);

									const msg = {
										type: 'downloadExtFail',
										fileName: filename,
										extName: val,
										extMap: extMap,
										extTotal: Object.keys(extMap).length,
									};
									if (that.win) that.win.webContents.send('kylinide.installWizard.msg', msg);
								}
							}).catch((error) => {

								console.log(`Download ${val} failed1: ${error}`);
								const msg = {
									type: 'downloadExtFail',
									fileName: filename ? filename : val,
									extName: val,
									extMap: extMap,
									// extTotal: Object.keys(extMap).length,
									extTotal: extList.length,
								};
								if (that.win) that.win.webContents.send('kylinide.installWizard.msg', msg);

							});
						}
					} catch (error) {
						console.log(`Download ${val} failed2: ${error}`);
						const msg = {
							type: 'downloadExtFail',
							fileName: val,
							extName: val,
							extMap: extMap,
							// extTotal: Object.keys(extMap).length,
							extTotal: extList.length,
						};
						if (that.win) that.win.webContents.send('kylinide.installWizard.msg', msg);

					} finally {
						// semaphore.release(); // 释放信号量
					}
				});

			});


			ipcMain.on('kylinide.installWizard.msg.process', async (event, msg) => {
				if (msg.type === 'installExt') {

					const logFile0 = installConfig + '/log/extInstall.1.log';

					if (!fs.existsSync(logFile0)) {
						fs.mkdirSync(installConfig + "/log", { recursive: true });
					}

					try {
						const installItem = extDownloadPath + msg.downloadDone;
						const installCommand = "kylin-code --install-extension " + installItem;
						if (installQueue.length === 0) {
							installQueue.push({ installCommand, msg });
							await executeNextInstall();
						}
						else {
							installQueue.push({ installCommand, msg });
						}

					} catch (error) {
						console.error(`执行出错: ${error.message}`);
					}
				}
				else if (msg.type === 'installPkg') {
					console.log("kylinide.installWizard.msg.process:installPkg");
					const extlogFile = installConfig + '/log/extInstall.log';
					backupLogFile(extlogFile)
					const extlogFile0 = installConfig + '/log/extInstall.1.log';
					fs.writeFileSync(extlogFile0, '');

					if (depList.length === 0) {
						const startDownloadExtMsg = {
							type: "extDownloadInit",
						}
						if (that.win)
							that.win.webContents.send("kylinide.installWizard.msg", startDownloadExtMsg);
						lastExtLogPosition = 0;

						fs.watch(extLogFile0, (eventType, filename) => {

							if (eventType === 'change') {
								// 获取文件的当前大小
								const stats = fs.statSync(extLogFile0);
								const currentSize = stats.size;

								// 计算更新部分的大小
								const updateSize = currentSize - lastExtLogPosition;
								if (updateSize <= 0) return;
								// 读取更新部分的内容
								const buffer = Buffer.alloc(updateSize);
								const fileDescriptor = fs.openSync(extLogFile0, 'r');
								fs.readSync(fileDescriptor, buffer, 0, updateSize, lastExtLogPosition);
								fs.closeSync(fileDescriptor);

								// 将更新部分的内容转换为字符串并输出
								const updatedContent = buffer.toString('utf8');

								// 更新上一次读取的位置
								lastExtLogPosition = currentSize;
								const installMsg = {
									type: "extInstallLogPre",
									data: updatedContent
								};

								if (that.win)
									that.win.webContents.send("kylinide.installWizard.msg", installMsg)

							}

						});
						return;
					}

					lastLogPosition = 0;
					lastExtLogPosition = 0;
					const logFile = installConfig + '/log/install.log';
					const resultFile = installConfig + '/resultFile';
					const installFile = installConfig + '/install.sh';
					const logFile0 = installConfig + '/log/install.1.log';
					backupLogFile(logFile);

					try {
						fs.writeFileSync(resultFile, '');
						fs.writeFileSync(installFile, '');
						fs.writeFileSync(logFile0, '');
						const installMsg = {
							type: "depStartInstall",
							depName: 'depStartInstall'
						};

						if (that.win)
							that.win.webContents.send("kylinide.installWizard.msg", installMsg)

						if (depList.length === 0) return;

						depList.forEach((packageName) => {
							const command = `apt-get install -y ${packageName} >> ${logFile0};\necho $? >> ${resultFile};\n`;
							fs.appendFileSync(installFile, command);
						});

						executeScriptWithPkexec(installFile);

					} catch (error) {
						console.log(error);
					}
				}
				else if (msg.type === 'installScript') {
					if (msg.script['file_name'].endsWith(".js")) {
						try {
							await this.loadAndInvokeFunction(selectObject.dirPath + '/' + msg.script['file_name'], "main");
							const scriptMsg = {
								type: "scriptExecSucc",
								depName: msg.script['file_name']
							};
							installUtils.logger.info("脚本执行成功" + selectObject.dirPath + '/' + msg.script['file_name']);
							if (that.win)
								that.win.webContents.send("kylinide.installWizard.msg", scriptMsg)
						} catch {
							const scriptMsg = {
								type: "scriptExecFail",
								depName: msg.script['file_name']
							};
							installUtils.logger.info("脚本执行失败" + selectObject.dirPath + '/' + msg.script['file_name']);
							if (that.win)
								that.win.webContents.send("kylinide.installWizard.msg", scriptMsg)
						}
					} else if (msg.script['file_name'].endsWith(".sh")) {
						let command = "sh " + selectObject.dirPath + '/' + msg.script['file_name'];
						// await executeCommand(command);
						executeCommand(command).then(res => {
							const scriptMsg = {
								type: "scriptExecSucc",
								depName: msg.script['file_name']
							};
							installUtils.logger.info("脚本执行成功" + selectObject.dirPath + '/' + msg.script['file_name']);
							if (that.win)
								that.win.webContents.send("kylinide.installWizard.msg", scriptMsg)
						}).catch(error => {
							const scriptMsg = {
								type: "scriptExecFail",
								depName: msg.script['file_name']
							};
							installUtils.logger.info("脚本执行失败" + selectObject.dirPath + '/' + msg.script['file_name']);
							if (that.win)
								that.win.webContents.send("kylinide.installWizard.msg", scriptMsg)
						});

					}
				} else if (msg.type == "cancel") {
					//1.结束监听
					//2.结束正在执行的进程，下载，插件安装，软件包安装
					if (installProcessId && installProcessId.pid && installProcessId.exitCode == null && flagPkexec == 0) {
						console.log("取消安装before");
						// var killcommand = `pkexec sudo pkill -TERM -P ${installProcessId.pid}`;
						var killcommand = `pkexec sudo pkill -f 'bash ${installConfig}/install.sh'`;
						const sudokill = spawn(killcommand, { shell: true, stdio: 'inherit' });

						sudokill.on('exit', (code, signal) => {
							if (code == 127) {
								console.log('授权失败', code);
								installUtils.logger.error("取消安装授权失败");
							} else {
								if (this.win) {
									this.win.webContents.send("kylinide.installWizard.removeFileLister", { type: 'installFile' });
									this.win.webContents.send("kylinide.installWizard.removeFileLister", { type: 'extFile' });
									this.win.webContents.send("kylinide.installWizard.removeFileLister", { type: 'pkgFile' });
								}
								controller.abort();
								installQueue.splice(0);
								//结束插件下载及安装
								if (that.win) {
									that.win.webContents.send("kylinide.installWizard.cancelinstall", { type: "cancelinstall" });
								}
							}
							console.log('kill Exit code:', code);
						});
						console.log("取消安装after");
					} else {
						if (this.win) {
							this.win.webContents.send("kylinide.installWizard.removeFileLister", { type: 'installFile' });
							this.win.webContents.send("kylinide.installWizard.removeFileLister", { type: 'extFile' });
							this.win.webContents.send("kylinide.installWizard.removeFileLister", { type: 'pkgFile' });
						}
						controller.abort();
						cancelFlag = true;
						installQueue.splice(0);
						//结束插件下载及安装
						if (that.win) {
							that.win.webContents.send("kylinide.installWizard.cancelinstall", { type: "cancelinstall" });
						}
					}
				}
			});

			async function executeNextInstall() {
				if (installQueue.length === 0) {
					return; // 队列为空，结束执行
				}
				if (cancelFlag) {
					installQueue.splice(0);
					return;
				}
				const { installCommand, msg } = installQueue[0];
				try {
					const extlogFile = installConfig + '/log/extInstall.1.log';

					let ret: { stdout: string, stderr: string } = await spawnCommand(installCommand) as { stdout: string; stderr: string; };
					if (ret.stdout)
						fs.appendFileSync(extlogFile, ret.stdout);
					// if (ret.stderr)
					// 	fs.appendFileSync(extlogFile, ret.stderr);

					const installMsg = {
						type: "extInstalled",
						extFileName: msg.downloadDone,
						// extTotal: Object.keys(extMap).length,
						extTotal: extList.length
					};
					if (that.win) {
						that.win.webContents.send("kylinide.installWizard.msg", installMsg);
					}
				} catch (error) {
					console.error(`执行出错: ${error.message}`);
					const extlogFile = installConfig + '/log/extInstall.1.log';
					fs.appendFileSync(extlogFile, installCommand);
					fs.appendFileSync(extlogFile, '\n');
					fs.appendFileSync(extlogFile, error.message);
					fs.appendFileSync(extlogFile, '\n');
					const installMsg = {
						type: "extInstalledFail",
						extFileName: msg.downloadDone,
						extTotal: extList.length,
						extName: msg.extName
					};
					if (that.win) {
						that.win.webContents.send("kylinide.installWizard.msg", installMsg);
					}
				}

				installQueue.shift(); // 执行完成后，将当前消息从队列中移除
				await executeNextInstall(); // 继续执行下一个消息
			}

			var flagPkexec = 0;
			function executeScriptWithPkexec(scriptPath: string) {
				flagPkexec = 0;
				console.log("executeScriptWithPkexec");
				try {
					const pkexecCommand = `pkexec sudo bash ${scriptPath}`;
					installProcessId =
						spawn(pkexecCommand, { shell: true, stdio: 'inherit' });

					installProcessId.on('exit', (code, signal) => {
						flagPkexec++;
						console.log('Exit code:', code);
						if (code == 127) {
							//授权失败，结束安装。
							if (that.win) {
								that.win.webContents.send("kylinide.installWizard.Auth", { type: "pkgNotAuth" });
							}
						}
					});
				} catch (error) {
					console.error(`执行脚本时出错: ${error.message}`);
					// return false;
				}
			}

			function spawnCommand(command: string) {
				return new Promise((resolve, reject) => {
					const child = spawn(command, { shell: true });

					let stdout = '';
					let stderr = '';

					child.stdout.on('data', (data) => {
						stdout += data.toString();
					});

					child.stderr.on('data', (data) => {
						stderr += data.toString();
					});

					child.on('close', (code) => {
						if (code === 0) {
							resolve({ stdout, stderr });
						} else {
							reject(new Error(`Command failed with exit code ${code} `));
						}
					});
				});
			}

			async function executeCommand(command: string) {
				return new Promise<void>((resolve, reject) => {
					const { exec } = require('child_process');
					exec(command, (error: any, stdout: any, stderr: any) => {
						if (error) {
							reject(error);
						} else {
							// console.log(`stdout: ${ stdout } `);
							// console.error(`stderr1: ${ stderr } `);
							resolve();
						}
					});
				});
			}
			//显示错误
			//arg 0 : title
			//arg 1 : content
			console.log('openInstallWizard()');

		});
	}

	private replaceBaseUrl(url: string, baseurl: string) {
		if (url.startsWith("base-url:")) {
			url = url.replace("base-url:", baseurl);
		}
		return url;
	}
	//ide是否首次启动，如果是首次启动返回true,否则返回false
	private async isFirstLoad(): Promise<boolean> {
		let res = false;
		const userDataPath = path.join(this.environmentMainService.userHome.fsPath, '.config', 'Kylin-Code', 'installconfig');
		const flagFilePath = path.join(userDataPath, 'first-run.flag');

		if (!fs.existsSync(userDataPath)) {
			fs.mkdirSync(userDataPath, { recursive: true }); // 递归创建目录
		}
		if (fs.existsSync(flagFilePath)) {
			res = false; // 标记文件存在，不是首次启动
		} else {
			fs.writeFileSync(flagFilePath, ''); // 创建标记文件
			res = true; // 标记文件不存在，是首次启动
		}
		return res;
	}
	private getPublicKeyPem(publicKeyPath: string) {
		const data = fs.readFileSync(publicKeyPath, 'utf-8');
		return data;
	}
	private versify(dataPath: string, signature: string) {
		const crypto = require('crypto');
		const publicKeyPath = path.join(__dirname, "./installWizard/key/public.pem");
		//获取数据
		const dataToSign = fs.readFileSync(dataPath, 'utf-8');

		var md5 = crypto.createHash('md5');
		var md5data = md5.update(dataToSign).digest('hex');
		//获取公钥
		var publicKeyPem = this.getPublicKeyPem(publicKeyPath);
		var publicKey = crypto.createPublicKey({ key: publicKeyPem, format: 'pem', type: 'pkcs1' });
		// 验证签名
		const verify = crypto.createVerify('RSA-SHA256');
		verify.update(md5data);
		const isVerified = verify.verify(publicKey, signature, 'hex');
		if (isVerified) {
			installUtils.logger.info("签名验证成功:" + dataPath);
		} else {
			installUtils.logger.info("签名验证失败:" + dataPath);
		}
		return isVerified
	}
	//下载文件
	private async download_File(url_git: string, dst: string, controller?: AbortController) {
		try {
			const response = await axios.get(url_git, { responseType: 'stream', timeout: 10000, signal: controller?.signal });
			const directoryPath = path.dirname(dst);
			// 判断目录是否存在
			if (!fs.existsSync(directoryPath)) {
				// 创建目录
				fs.mkdirSync(directoryPath, { recursive: true });
			}

			const writer = fs.createWriteStream(dst);
			response.data.pipe(writer);

			return new Promise((resolve, reject) => {
				writer.on('finish', () => {
					// console.log('文件已下载到本地:', dst);
					installUtils.logger.info("文件下载成功：" + dst);
					resolve(0);
				});

				writer.on('error', (err) => {
					console.error('写入文件时发生错误:', err);
					if (fs.existsSync(dst)) {
						fs.unlinkSync(dst);
					}
					reject(-1);
				});
			});
		} catch (error) {
			installUtils.logger.error("文件下载失败：" + dst);
			if (axios.isCancel(error)) {
				installUtils.logger.error('请求已取消');
			}
			else if (error.code === 'ECONNABORTED') {
				installUtils.logger.error("请求超时");
			} else {
				installUtils.logger.error('请求发生错误', error.message);
			}
			return Promise.reject(-1);
		}
	}

	private async localConfigVerify(configDir: string, IDEVersion: string) {
		try {
			var dst = path.join(configDir, "./g_index.json");
			var g_index_localDataObject = JSON.parse(fs.readFileSync(dst, 'utf-8'));
			let flag = 0;
			//获取到判断操作系统的脚本文件
			var match_script_file_name = g_index_localDataObject["match-script"]["file_name"];
			var match_script_file_sign = g_index_localDataObject["match-script"]["sign-md5"];
			var match_script_filePath = path.join(configDir, `${match_script_file_name}`);
			//获取到存放插件仓库的配置文件
			var match_ext_file_name = g_index_localDataObject["ext-file"]["file_name"];
			var match_ext_file_sign = g_index_localDataObject["ext-file"]["sign-md5"];
			var match_ext_filePath = path.join(configDir, `${match_ext_file_name}`);

			//校验本地数据是否有问题
			if (!this.versify(`${match_script_filePath}`, match_script_file_sign)) {
				flag++;
			}
			if (!this.versify(`${match_ext_filePath}`, match_ext_file_sign)) {
				flag++;
			}
			//执行脚本，获取操作系统信息
			const functionName = 'getosinfo';
			const osinfo = await this.loadAndInvokeFunction(match_script_filePath, functionName);
			installUtils.logger.info("通过脚本" + match_script_filePath + "获取操作系统信息" + osinfo);
			let localConfigMatch = 0;
			// 检测文件是否有osinfo想匹配的
			if (g_index_localDataObject["config-file"].hasOwnProperty(`${osinfo}`)) {
				if (installUtils.compareVersions(g_index_localDataObject['config-file'][osinfo][0]["kylin-ide-lowest-ver"], IDEVersion) == 1) {
					installUtils.logger.info("本地配置文件版本与当前ide版本不兼容");
					flag++;
				} else {
					if (!this.versify(path.join(installUtils.localConfigPath(), `${g_index_localDataObject['config-file'][osinfo][0]['file_name']}`), `${g_index_localDataObject['config-file'][osinfo][0]['sign-md5']}`)) {
						flag++;
					} else {
						localConfigMatch = 1;
					}
				}

				//校验相关的脚本文件
				var depFileName = g_index_localDataObject['config-file'][osinfo][0]['file_name'];
				var depObject = JSON.parse(fs.readFileSync(path.join(configDir, depFileName), 'utf-8'));
				Object.keys(depObject['second_class']).forEach((key) => {
					var object = depObject['second_class'][key]['script-list'];
					for (let i = 0; i < object.length; i++) {
						var file_name: string;
						var sign_md5: string;
						file_name = object[i]["file_name"];
						sign_md5 = object[i]["sign-md5"];
						if (!this.versify(path.join(configDir, file_name), sign_md5)) {
							installUtils.logger.error(path.join(configDir, file_name) + "文件校验失败");
							flag++;
						} else {
							console.log(path.join(configDir, file_name) + "文件校验正确");
						}
					}
				});

			} else {
				flag++;
			}

			let res = flag > 0 ? -1 : 0

			let configData = {
				res: res,
				g_index_Object: g_index_localDataObject,
				osinfo: osinfo,
				localConfigMatch: localConfigMatch,
				depConfigInfo: osinfo !== "undefined" ? g_index_localDataObject['config-file'][osinfo][0] : {}
			}
			return configData;
		} catch (error: any) {
			installUtils.logger.error("本地数据校验失败" + error);
			let configData = {
				res: -1,
				g_index_Object: "",
				osinfo: "",
				localConfigMatch: -1,
				depConfigInfo: {}
			}
			return configData;
		}
	}
	private async downloadAndVerify(updateConfigDir: string, arg: any) {
		updateConfigDir = arg.dst;
		const g_index_url = arg.url;
		try {
			const dst = updateConfigDir + '/g_index.json';
			if (!fs.existsSync(updateConfigDir)) {
				fs.mkdirSync(updateConfigDir, { recursive: true })
			}
			var g_index_Object;
			var flag = 0;
			let status = await this.download_File(g_index_url, dst);
			if (status === 0) {
				//读取全局文件
				g_index_Object = JSON.parse(fs.readFileSync(dst, 'utf-8'));
				//下载脚本文件
				let extLinkAddrPath = updateConfigDir + '/' + g_index_Object['ext-file']['file_name'];
				const res1 = await this.download_File(this.replaceBaseUrl(g_index_Object['ext-file']['file_url'], g_index_Object['base-url']), extLinkAddrPath);
				//下载插件配置文件
				const res2 = await this.download_File(this.replaceBaseUrl(g_index_Object['match-script']['file_url'], g_index_Object['base-url']), `${arg.dst}/${g_index_Object['match-script']['file_name']}`);
				if (res1 != 0 || res2 != 0) {
					flag++;
				}
			} else {
				flag++;
			}
			this.baseUrl = g_index_Object['base-url'];

			//获取到判断操作系统的脚本文件
			var match_script_file_name = g_index_Object["match-script"]["file_name"];
			var match_script_file_sign = g_index_Object["match-script"]["sign-md5"];
			var match_script_filePath = path.join(updateConfigDir, `./${match_script_file_name}`);
			//获取到存放插件仓库的配置文件
			var match_ext_file_name = g_index_Object["ext-file"]["file_name"];
			var match_ext_file_sign = g_index_Object["ext-file"]["sign-md5"];
			var match_ext_filePath = path.join(updateConfigDir, `./${match_ext_file_name}`);


			//校验本地数据是否有问题
			if (!this.versify(`${match_script_filePath}`, match_script_file_sign)) {
				flag++;
			}
			if (!this.versify(`${match_ext_filePath}`, match_ext_file_sign)) {
				console.log("app ext verifysign error");
				flag++;
			}
			//执行脚本，获取操作系统信息
			const functionName = 'getosinfo';
			let osinfo = await this.loadAndInvokeFunction(match_script_filePath, functionName);
			installUtils.logger.info("通过脚本" + match_script_filePath + "获取操作系统信息" + osinfo);

			let ConfigMatch = 0;
			// 检测文件是否有osinfo想匹配的
			if (osinfo !== 'undefined') {
				if (g_index_Object["config-file"].hasOwnProperty(`${osinfo}`)) {
					if (installUtils.compareVersions(g_index_Object['config-file'][osinfo][0]["kylin-ide-lowest-ver"], this.productService.IDEVersion) == 1) {
						installUtils.logger.info("网上的配置文件版本与当前ide版本不兼容");
						flag++;
					} else {
						//下载和当前操作系统关联的插件配置文件
						var depUrl = g_index_Object['config-file'][osinfo][0]['file_url'];
						var osConfigDst = updateConfigDir + '/' + g_index_Object['config-file'][osinfo][0]['file_name'];
						let status1 = await this.download_File(this.replaceBaseUrl(depUrl, g_index_Object['base-url']), osConfigDst);
						if (status1 === 0) {
							if (!this.versify(osConfigDst, g_index_Object['config-file'][osinfo][0]['sign-md5'])) {
								flag++;
							}
						} else {
							flag++;
						}
					}
					//校验相关的脚本文件
					var depFileName = g_index_Object['config-file'][osinfo][0]['file_name'];
					var depObject = JSON.parse(fs.readFileSync(path.join(updateConfigDir, depFileName), 'utf-8'));
					Object.keys(depObject['second_class']).forEach(async (key) => {
						var object = depObject['second_class'][key]['script-list'];
						for (let i = 0; i < object.length; i++) {
							var file_name: string;
							var sign_md5: string;
							var file_url: string;
							file_name = object[i]["file_name"];
							sign_md5 = object[i]["sign-md5"];
							file_url = object[i]['file_url'];

							const res = await this.download_File(this.replaceBaseUrl(file_url, this.baseUrl), path.join(updateConfigDir, file_name));
							if (res == 0) {
								if (!this.versify(path.join(updateConfigDir, file_name), sign_md5)) {
									installUtils.logger.error(path.join(updateConfigDir, file_name) + "文件校验失败");
									flag++;
								}
							} else {
								flag++;
							}
						}
					});

				} else {
					flag++;
				}
			} else {
				flag++;
			}
			let res = flag > 0 ? -1 : 0
			let configData = {
				res: res,
				g_index_Object: g_index_Object,
				osinfo: osinfo,
				ConfigMatch: ConfigMatch,
				base_url: g_index_Object['base-url'],
				depConfigInfo: osinfo !== "undefined" ? g_index_Object['config-file'][osinfo][0] : {}
			}
			return configData;
		} catch (error) {
			installUtils.logger.error("网络数据校验失败" + error);
			let configData = {
				res: -1,
				g_index_Object: {},
				osinfo: "",
				ConfigMatch: -1,
				base_url: "",
				depConfigInfo: {}
			}
			return configData;
		}

	}


	private async loadAndInvokeFunction(modulePath: string, functionName: string, ...args: any[]): Promise<any> {
		try {
			const module = await import(modulePath);
			if (typeof module[functionName] === 'function') {
				const result = await module[functionName](...args);
				return result;
			} else {
				throw new Error(`Function '${functionName}' not found in module '${modulePath}'.`);
			}
		} catch (error) {
			throw new Error(`Failed to load module '${modulePath}': ${error}`);
		}
	}


}

